<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" style="margin-top: 32px">
      <el-tab-pane label="欠费租户缴费" name="arrears">
        <!-- 欠费租户 table 与搜索区 -->
        <el-form :inline="true">
          <el-form-item label="租户名称">
            <el-input v-model="tenantQuery.qymc" placeholder="请输入租户名称" style="width: 180px" />
          </el-form-item>
          <el-form-item label="载体">
            <el-select v-model="tenantQuery.bm" placeholder="请选择载体" style="width: 180px">
              <el-option v-for="item in ztOptions" :key="item.nr" :label="item.nr" :value="item.nr" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleTenantQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetTenantQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="tenantList" style="margin-bottom: 18px">
          <el-table-column prop="qymc" label="租户名称" align="center">
            <template #default="scope">
              <span class="tenant-blue" @click="openTenantDrawer(scope.row)">{{ scope.row.qymc }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="jflx" label="缴费类型" align="center">
            <template #default="scope">
              <span>{{ scope.row.jflx == 1 ? "后付费" : scope.row.jflx == 2 ? "预付费" : "未知" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="wfksjec" label="未收金额(元)" align="center" />
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="openTenantDrawer(scope.row)">立即缴费</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="tenantTotal > 0" :total="tenantTotal" v-model:page="tenantQuery.pageNum" v-model:limit="tenantQuery.pageSize" @pagination="getTenantListData" />
      </el-tab-pane>
      <el-tab-pane label="停电租户提醒" name="poweroff">
        <!-- 停电租户 table 与搜索区 -->
        <el-form :inline="true">
          <el-form-item label="租户名称">
            <el-input v-model="poweroffQuery.qymc" placeholder="请输入租户名称" style="width: 180px" />
          </el-form-item>
          <el-form-item label="载体">
            <el-select v-model="poweroffQuery.zt" placeholder="请选择载体" style="width: 180px">
              <el-option v-for="item in ztOptions" :key="item.nr" :label="item.nr" :value="item.nr" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handlePoweroffQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetPoweroffQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="poweroffList" style="margin-bottom: 18px">
          <el-table-column prop="qymc" label="租户名称" align="center" />
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="jflx" label="缴费类型" align="center">
            <template #default="scope">
              <span>{{ scope.row.jflx == 1 ? "后付费" : scope.row.jflx == 2 ? "预付费" : "未知" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="qfje" label="欠费金额(元)" align="center" />
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button type="warning" size="small" @click="sendPoweroffNotice(scope.row)">停电通知</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="poweroffTotal > 0" :total="poweroffTotal" v-model:page="poweroffQuery.pageNum" v-model:limit="poweroffQuery.pageSize" @pagination="getPoweroffListData" />
      </el-tab-pane>
    </el-tabs>
    <!-- 侧边抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerQymc + ' - 待缴费详情'"
      size="60%"
      direction="rtl"
      destroy-on-close
    >
      <!-- 数据看板 -->
      <div class="dashboard beautify-board" style="margin-bottom: 18px">
        <div class="dashboard-row">
          <div class="dashboard-item board-blue">
            <span class="label">未收金额</span>
            <span class="value">{{ tenantBoard.wfksjec || 0 }}</span>
          </div>
          <div class="dashboard-item board-orange">
            <span class="label">滞纳金</span>
            <span class="value">{{ tenantBoard.znjec || 0 }}</span>
          </div>
          <div class="dashboard-item board-green">
            <span class="label">应收金额</span>
            <span class="value">{{ tenantBoard.hkjeb || 0 }}</span>
          </div>
        </div>
      </div>
      <div style="margin: 18px 0; text-align: right">
        <el-button
          type="primary"
          @click="openBatchPayDialog"
          :disabled="!selectedUnpaidRows.length"
          >批量缴费</el-button
        >
      </div>
      <!-- 未收账单列表 -->
      <el-table
        :data="unpaidList"
        @selection-change="handleUnpaidSelectionChange"
        style="margin-bottom: 10px"
        ref="unpaidTable"
        :row-key="(row) => row.hkid"
        :border="true"
        :highlight-current-row="true"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="hkid" label="账单号" align="center" width="120" />
        <el-table-column prop="hklx" label="费用类型" align="center" width="120" />
        <el-table-column prop="hkks" label="统计开始" align="center" width="120" />
        <el-table-column prop="hkjs" label="统计结束" align="center" width="120" />
        <el-table-column prop="hkje" label="应缴费(元)" align="center" width="120" />
        <el-table-column prop="znje" label="滞纳金(元)" align="center" width="120" />
        <el-table-column prop="wsje" label="未收金额(元)" align="center" width="120" />
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openSinglePayDialog(scope.row)"
              >立即缴费</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px 0; text-align: right">
        未收账单合计：<span style="color: #e43d33">{{ unpaidTotalAmmeter }}</span> 元
      </div>
      <pagination
        v-show="unpaidTotal > 0"
        :total="unpaidTotal"
        v-model:page="unpaidPage"
        v-model:limit="unpaidPageSize"
        @pagination="getUnpaidList"
      />

      <!-- 批量缴费弹窗 -->
      <el-dialog
        title="批量缴费"
        v-model="batchPayDialogVisible"
        width="400px"
        :close-on-click-modal="false"
      >
        <div style="margin-bottom: 10px">
          <div>
            该租户总账单金额：<span style="color: #209ff0">{{
              tenantBoard.wfksjec || 0
            }}</span>
            元
          </div>
          <div>
            勾选账单总金额：<span style="color: #e43d33">{{ batchPayTotal }}</span> 元
          </div>
        </div>
        <el-form :model="batchPayForm" label-width="90px">
          <el-form-item label="缴费金额" prop="ysje">
            <el-input v-model="batchPayForm.ysje" placeholder="请输入缴费金额" />
          </el-form-item>
          <el-form-item label="缴费日期" prop="sjrq">
            <!-- <el-date-picker v-model="batchPayForm.sjrq" type="date" placeholder="请选择日期" :default-value="new Date()" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /> -->
         <el-date-picker
              v-model="singlePayForm.sjrq"
              type="date"
              placeholder="请选择日期"
              :default-value="new Date()"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledFutureDate"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="batchPayForm.remark" placeholder="请输入备注" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="batchPayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchPay">确定缴费</el-button>
        </template>
      </el-dialog>
      <!-- 单账单缴费弹窗 -->
      <el-dialog
        title="立即缴费"
        v-model="singlePayDialogVisible"
        width="400px"
        :close-on-click-modal="false"
      >
        <div style="margin-bottom: 10px">
          <div>
            账单金额：<span style="color: #e43d33">{{ singlePayRow.wsje }}</span> 元
          </div>
        </div>
        <el-form :model="singlePayForm" label-width="90px">
          <el-form-item label="缴费金额" prop="ysje">
            <el-input v-model="singlePayForm.ysje" placeholder="请输入缴费金额" />
          </el-form-item>
          <el-form-item label="缴费日期" prop="sjrq">
            <!-- <el-date-picker v-model="singlePayForm.sjrq" type="date" placeholder="请选择日期" :default-value="new Date()" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /> -->
         <el-date-picker
              v-model="batchPayForm.sjrq"
              type="date"
              placeholder="请选择日期"
              :default-value="new Date()"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledFutureDate"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="singlePayForm.remark" placeholder="请输入备注" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="singlePayDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSinglePay">确定缴费</el-button>
        </template>
      </el-dialog>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { getTenantList, receivableDetailCustomerList, simulatePayment,getPowerOffTenantList,getPowerOffNotice } from "@/api/bill";
import { selectzt } from "@/api/carrier/ammeter";
import { parseTime } from "@/utils/ruoyi";
const { proxy } = getCurrentInstance();
const activeTab = ref("arrears");
// 租户列表
const tenantQuery = reactive({ qymc: "", bm: "", pageNum: 1, pageSize: 10, dbqx: 3 });
const tenantList = ref([]);
const tenantTotal = ref(0);
const disabledFutureDate = (time) => {
  return time.getTime() > Date.now();
};
function getTenantListData() {
  getTenantList({ ...tenantQuery }).then(res => {
    tenantList.value = res.data?.list || [];
    tenantTotal.value = res.data?.total || 0;
  });
}
function onSearch() {
  tenantQuery.pageNum = 1;
  getTenantListData();
}
// 未收账单列表
const unpaidList = ref([]);
const unpaidTotal = ref(0);
const unpaidPage = ref(1);
const unpaidPageSize = ref(10);
// 合计未收账单金额（保留两位小数）
const unpaidTotalAmmeter = ref(0);
// function getUnpaidList() {
//   receivableDetailCustomerList({
//     khbh: drawerKhbh.value,
//     zt: drawerZt.value,
//     pageNum: unpaidPage.value,
//     pageSize: unpaidPageSize.value,
//   }).then(res => {
//     const arr = res.data?.["电费未收列表"].list || [];
//     unpaidList.value = arr.map((item) => ({
//       ...item,
//       hkks: item.hkks ? parseTime(item.hkks, "{y}-{m}-{d}") : "--",
//       hkjs: item.hkjs ? parseTime(item.hkjs, "{y}-{m}-{d}") : "--",
//       hkrq: item.hkrq ? parseTime(item.hkrq, "{y}-{m}-{d}") : "--",
//     }));
//     unpaidTotal.value = res.data?.["电费未收列表"].total || 0;
//     // 合计金额保留两位小数
//     const total = arr.reduce((sum, item) => sum + (Number(item.wsje) || 0), 0);
//     unpaidTotalAmmeter.value = total.toFixed(2);
//   });
// }

// 抽屉相关
const drawerVisible = ref(false);
const drawerKhbh = ref("");
const drawerQymc = ref("");
const drawerZt = ref("");
const tenantBoard = ref({});
function openTenantDrawer(row) {
  drawerKhbh.value = row.khbh;
  drawerQymc.value = row.qymc;
  drawerZt.value = row.zt;
  tenantBoard.value = row;
  drawerVisible.value = true;
  unpaidPage.value = 1;
  getUnpaidList();
}


function getUnpaidList() {
  receivableDetailCustomerList({
    khbh: drawerKhbh.value,
    zt: drawerZt.value,
    pageNum: unpaidPage.value,
    pageSize: unpaidPageSize.value,
  }).then(res => {
    const arr = res.data?.["电费未收列表"].list || [];

   unpaidList.value = arr.map((item) => ({
      ...item,
      hkks: item.hkks ? parseTime(item.hkks, "{y}-{m}-{d}") : "--",
      hkjs: item.hkjs ? parseTime(item.hkjs, "{y}-{m}-{d}") : "--",
      hkrq: item.hkrq ? parseTime(item.hkrq, "{y}-{m}-{d}") : "--",
    }));
    unpaidTotal.value = res.data?.["电费未收列表"].total || 0;
    // 合计金额保留两位小数
    const total = arr.reduce((sum, item) => sum + (Number(item.wsje) || 0), 0);
    unpaidTotalAmmeter.value = total.toFixed(2);
 });
 
}

// 勾选与批量缴费
const selectedUnpaidRows = ref([]);
function handleUnpaidSelectionChange(rows) {
  selectedUnpaidRows.value = rows;
}
const batchPayDialogVisible = ref(false);
const batchPayForm = reactive({ ysje: '', sjrq: '' });
const batchPayTotal = ref(0);
function openBatchPayDialog() {
  let total = 0;
  selectedUnpaidRows.value.forEach(row => {
    total += Number(row.wsje) || 0;
  });
  batchPayTotal.value = total;
  batchPayForm.ysje = total.toFixed(2);
  batchPayForm.sjrq = new Date().toISOString().slice(0, 10); // 默认当天 yyyy-mm-dd
  batchPayDialogVisible.value = true;
}
function submitBatchPay() {
  if (!batchPayForm.ysje || isNaN(Number(batchPayForm.ysje)) || Number(batchPayForm.ysje) <= 0) {
    proxy.$modal.msgWarning("请输入正确的缴费金额");
    return;
  }
  // if (Number(batchPayForm.ysje) > batchPayTotal.value) {
  //   proxy.$modal.msgWarning("缴费金额不能大于勾选账单总额");
  //   return;
  // }
  if (!batchPayForm.sjrq) {
    proxy.$modal.msgWarning("请选择缴费日期");
    return;
  }
  const ids = selectedUnpaidRows.value.map(row => row.hkid);
  simulatePayment({
    hkid: ids.join(","),
    zhkje: batchPayForm.ysje,
    khbh: drawerKhbh.value,
    zt: drawerZt.value,
    qymc: drawerQymc.value,
    zjly: "缴费",
    sjrq: batchPayForm.sjrq,
    remark: batchPayForm.remark
  }).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("批量缴费成功");
      batchPayDialogVisible.value = false;
      getUnpaidList();
      selectedUnpaidRows.value = [];
    } else {
      proxy.$modal.msgError(res.msg || "批量缴费失败");
    }
  });
}

// 单账单缴费
const singlePayDialogVisible = ref(false);
const singlePayRow = ref({});
const singlePayForm = reactive({ ysje: '', sjrq: '' });
function openSinglePayDialog(row) {
  singlePayRow.value = row;
  singlePayForm.ysje = row.wsje;
  singlePayForm.sjrq = new Date().toISOString().slice(0, 10); // 默认当天
  singlePayDialogVisible.value = true;
}
function submitSinglePay() {
  if (!singlePayForm.ysje || isNaN(Number(singlePayForm.ysje)) || Number(singlePayForm.ysje) <= 0) {
    proxy.$modal.msgWarning("请输入正确的缴费金额");
    return;
  }
  // if (Number(singlePayForm.ysje) > Number(singlePayRow.value.wsje)) {
  //   proxy.$modal.msgWarning("缴费金额不能大于账单金额");
  //   return;
  // }
  if (!singlePayForm.sjrq) {
    proxy.$modal.msgWarning("请选择缴费日期");
    return;
  }
  simulatePayment({
    hkid: singlePayRow.value.hkid,
    zhkje: singlePayForm.ysje,
    khbh: drawerKhbh.value,
    zt: drawerZt.value,
    qymc: drawerQymc.value,
    zjly: "缴费",
    sjrq: singlePayForm.sjrq,
    remark: singlePayForm.remark
  }).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("缴费成功");
      singlePayDialogVisible.value = false;
      getUnpaidList();
    } else {
      proxy.$modal.msgError(res.msg || "缴费失败");
    }
  });
}

// 载体选项
const ztOptions = ref([]);
function fetchZtOptions() {
  selectzt({ pageNum: 1, pageSize: 10, lxbh: 1 }).then(res => {
    ztOptions.value = res.data?.list || [];
    if (ztOptions.value.length > 0 && !tenantQuery.bm) {
      tenantQuery.bm = ztOptions.value[0].nr;
      poweroffQuery.zt = ztOptions.value[0].nr;
    }
    getTenantListData();
    getPoweroffListData()
  });
}
function handleTenantQuery() {
  tenantQuery.pageNum = 1;
  getTenantListData();
}
function resetTenantQuery() {
  tenantQuery.qymc = "";
  tenantQuery.bm = ztOptions.value[0]?.nr;
  tenantQuery.pageNum = 1;
  getTenantListData();
}
// 停电租户相关
const poweroffQuery = reactive({ qymc: "", zt: "", pageNum: 1, pageSize: 10 });
const poweroffList = ref([]);
const poweroffTotal = ref(0);
function getPoweroffListData() {
  getPowerOffTenantList({ ...poweroffQuery }).then(res => {
    poweroffList.value = res.data?.list || [];
    poweroffTotal.value = res.data?.total || 0;
  });
}
function handlePoweroffQuery() {
  poweroffQuery.pageNum = 1;
  getPoweroffListData();
}
function resetPoweroffQuery() {
  poweroffQuery.qymc = "";
  poweroffQuery.zt = ztOptions.value[0]?.nr || "";
  poweroffQuery.pageNum = 1;
  getPoweroffListData();
}
function sendPoweroffNotice(row) {
  getPowerOffNotice({ khbh: row.khbh, zt: row.zt, qymc: row.qymc }).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("已发送停电通知");
    } else {
      proxy.$modal.msgError(res.msg || "发送失败");
    }
  });
}
onMounted(() => {
  fetchZtOptions();
  // getPoweroffListData();
});
</script>

<style scoped>
.tenant-blue {
  color: #209ff0;
  cursor: pointer;
  font-weight: bold;
}
.dashboard {
  background: #fafdff;
  border-radius: 18px;
  box-shadow: 0 4px 18px rgba(32, 159, 240, 0.1);
  padding: 28px 18px 18px 18px;
  margin-bottom: 36px;
}
.dashboard-row {
  display: flex;
  justify-content: space-between;
  gap: 18px;
  margin-bottom: 0;
}
.dashboard-item {
  flex: 1;
  margin-right: 0;
  border-radius: 14px;
  padding: 22px 0 16px 0;
  text-align: center;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.06);
  border: 1.5px solid #e6f3fc;
  transition: box-shadow 0.2s;
  position: relative;
  overflow: hidden;
  color: #fff;
}
.dashboard-item:not(:last-child) {
  margin-right: 18px;
}
.label {
  font-size: 16px;
  color: #fff;
  display: block;
  margin-bottom: 10px;
  letter-spacing: 1px;
  font-weight: 500;
}
.value {
  font-size: 30px;
  font-weight: bold;
  color: #fff;
  display: block;
  letter-spacing: 1px;
  line-height: 1.2;
}
.board-blue {
  background-color: #209ff0;
  color: #fff;
}
.board-green {
  background-color: #67c23a;
  color: #fff;
}
.board-orange {
  color: #fff;
  background-color: #faad14;
}
</style>
